package com.saris.primego.dao;

import com.saris.primego.pojo.dto.ProductSalesSummaryDTO;
import com.saris.primego.pojo.entity.OrderDetail;
import io.lettuce.core.dynamic.annotation.Param;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;

@Repository
public interface OrderDetailRepository extends JpaRepository<OrderDetail, Long>, JpaSpecificationExecutor<OrderDetail> {
    List<OrderDetail> findAllByOrderId(Long orderId);

    List<OrderDetail> getAllByOrderId(Long orderId);

    @Query("SELECT " +
            "NEW com.saris.primego.pojo.dto.ProductSalesSummaryDTO( " +
            "   od.name, " +
            "   SUM(od.number)) " +
            "FROM OrderDetail od " +
            "JOIN Orders o ON od.orderId = o.id " +
            "WHERE o.status = :status " +
            "  AND o.orderTime BETWEEN :startTime AND :endTime " +
            "  AND (od.dishId IS NOT NULL OR od.setmealId IS NOT NULL) " +
            "GROUP BY od.name " +
            "ORDER BY SUM(od.number) DESC")
    List<ProductSalesSummaryDTO> findTopSellingProducts(
            @Param("status") Integer status,
            @Param("startTime") LocalDateTime startTime,
            @Param("endTime") LocalDateTime endTime,
            Pageable pageable);
}
